<?php
namespace message\service;

/**--tmpl-use--**/
use herosphp\core\Loader;
use herosphp\utils\Page;
use models\MessageRemindModel;
use utils\x1\MyFunction;
use herosphp\bean\Beans;
use message\service\TriggerNodeService;

Loader::import('message.service.TriggerNodeService');
Loader::import('utils.x1.MyFunction');
Loader::import('message.service.SmsService');
Loader::import('utils.sms.ProviderFactory');

class RemindService extends CommonService
{
    private $thisModel = null;

    public function __construct($model)
    {
        parent::__construct($model);

        $this->thisModel = Loader::model('messageRemind');
    }

    //站内信搜索
    public function search($pagesize, $page, $searchArr)
    {

        $offset = $pagesize * ($page - 1); //计算记录偏移量

        $whereSql = "And remind.to_way = '" . $searchArr['to_way'] . "' And remind.app_id='" . appId() . "'";

        if ( $searchArr['id'] ){
            $whereSql .= " And remind.id in {$searchArr['id']}";
        }
        if (in_array($searchArr['select_mix_option1'], array('member_no', 'tmpl_name'))) {
            switch ($searchArr['select_mix_option1']) {
                case 'member_no':
                    $whereSql .= " And member.username Like '%{$searchArr['select_mix_option_value1']}%'";
                    break;
                case 'tmpl_name':
                    $whereSql .= " And remind.tmpl_name Like '%{$searchArr['select_mix_option_value1']}%'";
                    break;
            }
        }
        if (($searchArr['start_time'] != '' || $searchArr['end_time'] != '') && in_array($searchArr['select_mix_option2'], array('to_time'))) {
            switch ($searchArr['select_mix_option2']) {
                case 'to_time':
                    $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(remind.to_time)', strtotime($searchArr['start_time']), strtotime($searchArr['end_time']));
                    break;
            }
        }

        if ($searchArr['manager_name'] != '' && $searchArr['manager_name'] != 'all') {
            if($searchArr['manager_name']=='system'){

                $whereSql .= " And remind.manager_id ='0'";

            }else{

                $whereSql .= " And manager.username Like '%" . $searchArr['manager_name'] . "%'";
           }
        }


        $count_sql = "Select  count(*)
                From message_remind  As remind
                Left Join member  On remind.to_member_id=member.id
                Left Join admin_manager as manager On remind.manager_id=manager.id
                Where 1 $whereSql";
        $total = $this->thisModel->getDB()->excute($count_sql)->fetchColumn();

        //分页查询
        $pageinationSql = isset ($offset) ? " Limit $offset,$pagesize" : " Limit 0,$pagesize";

        $sql = "Select remind.*,member.username As member_username,manager.username As manager_name
                From message_remind  As remind
                Left Join member  On remind.to_member_id=member.id
                Left Join admin_manager as manager On remind.manager_id=manager.id
                Where 1 $whereSql
                Order By remind.to_time Desc $pageinationSql";

        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);



        return array("items" => $items, "total" => $total);
    }

    //站内信规则搜索
    public function searchByRule($pagesize, $page, $searchArr)
    {

        $offset = $pagesize * ($page - 1); //计算记录偏移量

        $whereSql = "And remind_rule.to_way = '" . $searchArr['to_way'] . "' And remind_rule.app_id='" . appId() . "'";

        if (in_array($searchArr['select_mix_option1'], array('rule_name'))) {
            switch ($searchArr['select_mix_option1']) {
                case 'rule_name':
                    $whereSql .= " And remind_rule.name Like '%{$searchArr['select_mix_option_value1']}%'";
                    break;
            }
        }

        if (($searchArr['start_time'] != '' || $searchArr['end_time'] != '') && in_array($searchArr['select_mix_option2'], array('addtime'))) {
            switch ($searchArr['select_mix_option2']) {
                case 'addtime':
                    $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(remind_rule.addtime)', strtotime($searchArr['start_time']), strtotime($searchArr['end_time']));
                    break;
            }
        }

        if ($searchArr['trigger_node'] != '' && $searchArr['trigger_node'] != 'all') {

            $whereSql .= " And remind_rule.trigger_node='" . $searchArr['trigger_node']."'";
        }
        if ($searchArr['status'] != '' && $searchArr['status'] != 'all') {

            $whereSql .= " And remind_rule.status=" . $searchArr['status'];
        }

        $count_sql = "Select  count(*)
                From message_remind_rule As remind_rule
                Left Join message_remind_tmpl As remind_tmpl On remind_rule.tmpl_id=remind_tmpl.id
                Left Join admin_manager as manager On remind_rule.manager_id=manager.id
                Where 1 $whereSql";
        $total = $this->thisModel->getDB()->excute($count_sql)->fetchColumn();

        //分页查询
        $pageinationSql = isset ($offset) ? " Limit $offset,$pagesize" : " Limit 0,$pagesize";

        $sql = "Select remind_rule.*,remind_tmpl.name As tmpl_name,manager.username As manager_name
                From message_remind_rule As remind_rule
                Left Join message_remind_tmpl As remind_tmpl On remind_rule.tmpl_id=remind_tmpl.id
                Left Join admin_manager as manager On remind_rule.manager_id=manager.id
                Where 1 $whereSql
                Order By remind_rule.addtime Desc $pageinationSql";

        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);



        return array("items" => $items, "total" => $total);
    }

    //站内信模板搜索
    public function searchByTmpl($pagesize, $page, $searchArr)
    {

        $offset = $pagesize * ($page - 1); //计算记录偏移量

        $whereSql = "And remind_tmpl.to_way = '" . $searchArr['to_way'] . "' And remind_tmpl.app_id='" . appId() . "'";

        if (in_array($searchArr['select_mix_option1'], array('tmpl_name'))) {
            switch ($searchArr['select_mix_option1']) {
                case 'tmpl_name':
                    $whereSql .= " And remind_tmpl.name Like '%{$searchArr['select_mix_option_value1']}%'";
                    break;
            }
        }

        if (($searchArr['start_time'] != '' || $searchArr['end_time'] != '') && in_array($searchArr['select_mix_option2'], array('addtime'))) {
            switch ($searchArr['select_mix_option2']) {
                case 'addtime':
                    $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(remind_tmpl.addtime)', strtotime($searchArr['start_time']), strtotime($searchArr['end_time']));
                    break;
            }
        }

        if ($searchArr['manager_name'] != '' && $searchArr['manager_name'] != 'all') {

            $whereSql .= " And manager.username Like '%" . $searchArr['manager_name'] . "%'";
        }

        if ($searchArr['status'] != '' && $searchArr['status'] != 'all') {

            $whereSql .= " And remind_tmpl.status=" . $searchArr['status'];
        }

        $count_sql = "Select  count(*)
                From message_remind_tmpl As remind_tmpl
                Left Join admin_manager as manager On remind_tmpl.manager_id=manager.id
                Where 1 $whereSql";
        $total = $this->thisModel->getDB()->excute($count_sql)->fetchColumn();

        //分页查询
        $pageinationSql = isset ($offset) ? " Limit $offset,$pagesize" : " Limit 0,$pagesize";

        $sql = "Select remind_tmpl.*,manager.username As manager_name
                From message_remind_tmpl As remind_tmpl
                Left Join admin_manager as manager On remind_tmpl.manager_id=manager.id
                Where 1 $whereSql
                Order By remind_tmpl.addtime Desc $pageinationSql";

        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);



        return array("items" => $items,  "total" => $total);
    }

    public function getRemindById($id)
    {
        $sql = "Select remind.*,manager.username As manager_name
                From message_remind  As remind
                Left Join admin_manager as manager On remind.manager_id=manager.id
                Where remind.id='$id' And remind.app_id='" . appId() . "'";
        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);

        return $items[0];
    }

    public function getRemindTmplById($id)
    {
        return Loader::model('messageRemindTmpl')->getItem($id);
    }

    //获取所有模板
    public function getRemindTmpls($toWay)
    {
        $tmplTtems = Loader::model('messageRemindTmpl')->getItems(array('status'=>'1','to_way' => $toWay));
        $option_arr = array();

        foreach ($tmplTtems as $k => $v) {
            $option_arr[$v['id']] = $v['name'];
        }
        return $option_arr;
    }

    /**
     * 根据规则名获取规则
     * @param $ruleName 规则名
     * @param $toWay 　规则类型
     * @return mixed
     */
    public function getRuleByTrigger($ruleName, $toWay)
    {
        return Loader::model('messageRemindRule')->getItem(array('name' => $ruleName, 'to_way' => $toWay));
    }

    /**
     * 预置４个节点到相关action中，触发提醒，尝试匹配规则，不匹配，则不提醒
     * @param $ruleName 节点名
     * @param $data 模板变量
     * @param $to_member_id 发送会员
     * @return bool
     */
    public function commandRemind($ruleName, $data,$to_member_id){

        if(!isset($data['验证码'])){//当发送的内容含有验证码时，不添加到站内信里
            $this->commandBySiteRemind($ruleName, $data,$to_member_id);
        }

        $this->commandBySmsRemind($ruleName, $data,$to_member_id);

    }
    /**
     * 预置４个节点到相关action中，触发提醒，尝试匹配规则，不匹配，则不提醒
     * @param $ruleName 节点名
     * @param $data 模板变量
     * @param $to_member_id 发送会员
     * @return bool
     */
    public function commandBySiteRemind($ruleName, $data, $to_member_id)
    {
        $memberService = Beans::get('member.member.service');
        $rule = $this->getRuleByTrigger($ruleName, MessageRemindModel::TO_WAY_SITE_REMIND);

        $tmpl = $this->getRemindTmplById($rule['tmpl_id']);

        $member = $memberService->getUsernameById($to_member_id);

        if ($rule['status'] == 1  && $tmpl) {
            if($data['平台名称']==''){

                $data['平台名称']=C('site_name');
            }
            if($data['短信签名']==''){

                $data['短信签名']=C('sms_sign');
            }
            if($data['客服热线']==''){

                $data['客服热线']=C('cs_phone');
            }
            if($data['会员昵称']==''){

                $data['会员昵称']= $member['nickname'];
            }
            $addData = array(
                'to_member_id' => $to_member_id,
                'to_member_moblie' => $member['username'],
                'manager_id' => 0,
                'to_time' => myNow(),
                'to_content' => $this->getRemindContent($rule['tmpl_id'], $data),
                'tmpl_id' => $rule['tmpl_id'],
                'tmpl_name' => $tmpl['name'],
                'to_status' => 1,
                'is_read' => 0,
                'to_way' => MessageRemindModel::TO_WAY_SITE_REMIND,
            );

            return $this->thisModel->add($addData);

        } else {

            return false;
        }


    }



    /**
     * 预置４个节点到相关action中，触发提醒，尝试匹配规则，不匹配，则不提醒
     * @param $ruleName 节点名
     * @param $data 模板变量
     * @param $to_member_id 发送会员
     * @param string $to_member_moblie 接受手机
     * @return bool
     */
    public function commandBySmsRemind($ruleName, $data,$to_member_id,$to_member_moblie='')
    {
        $memberService = Beans::get('member.member.service');

        $rule = $this->getRuleByTrigger($ruleName, MessageRemindModel::TO_WAY_SMS_REMIND);

        $tmpl = $this->getRemindTmplById($rule['tmpl_id']);

        if($to_member_id!=''){

            $to_member = $memberService->getUsernameById($to_member_id);

            if($to_member_moblie==''){

                $to_member_moblie = $to_member['username'];
            }
        }


        if ($rule['status'] == 1 && $to_member_moblie && $tmpl) {

            if($data['平台名称']==''){

                $data['平台名称']=C('site_name');
            }
            if($data['短信签名']==''){

                $data['短信签名']=C('sms_sign');
            }
            if($data['客服热线']==''){

                $data['客服热线']=C('cs_phone');
            }
            if($data['会员昵称']==''&&$to_member){

                $data['会员昵称']= $to_member['nickname'];
            }


            $addData = array(
                'to_member_id' => $to_member_id,
                'to_member_moblie' => $to_member_moblie,
                'manager_id' => 0,
                'to_time' => myNow(),
                'to_content' => $this->getRemindContent($rule['tmpl_id'], $data),
                'tmpl_id' => $rule['tmpl_id'],
                'tmpl_name' => $tmpl['name'],
                'to_status' => 1,
                'is_read' => 0,
                'to_way' => MessageRemindModel::TO_WAY_SMS_REMIND,
            );

            if ($this->thisModel->add($addData)) {

                $smsService = new SmsService();

                return $smsService->send($to_member_moblie, $addData['to_content']);//发送短信
            } else {

                return false;
            }

        } else {

            return false;
        }

    }

    /**
     * 用模板和数据来生成消息内容
     * @param $message_name
     * @param $data
     */
    public function getRemindContent($tmplId, $data)
    {
        $tmpl = $this->getRemindTmplById($tmplId);

        $tmplContent = $tmpl['content'];

        $kArr = array();
        $vArr = array();

        foreach ($data as $k => $v) {

            $kArr[] = '{' . $k . '}';
            $vArr[] = $v;
        }

        return str_replace($kArr, $vArr, $tmplContent);

    }
    //发送状态(0=未发送,1=已发送,2=发送失败)
    public function getRemindToStatusText($k = '__all')
    {
        //状态(0=禁用，1=启用)
        $arr = array(
            '0' => '未发送',
            '1' => '已发送',
            '2' => '发送失败',

        );
        return $k == '__all' ? $arr : $arr[$k];
    }
    //获取触发节点
    public function getRemindRuleTriggerNodeText($k = '__all')
    {
        $triggerNodeService = new TriggerNodeService();

        $arr=array();

        foreach($triggerNodeService->getTrggerNodeArr() as $key=>$value){

            $arr[$key]=$value['name_zh'];
        }

        return $k == '__all' ? $arr : $arr[$k];
    }

    //状态
    public function getRemindRuleStatusText($k = '__all')
    {
        //状态(0=禁用，1=启用)
        $arr = array(
            '0' => '禁用',
            '1' => '启用',
        );
        return $k == '__all' ? $arr : $arr[$k];
    }

    //状态
    public function getRemindTmplStatusText($k = '__all')
    {
        //状态(0=禁用，1=启用)
        $arr = array(
            '0' => '禁用',
            '1' => '启用',
        );
        return $k == '__all' ? $arr : $arr[$k];
    }

    //已读状态
    public function getRemindIsreadText($k = '__all')
    {
        //状态(0=禁用，1=启用)
        $arr = array(
            '0' => '未读',
            '1' => '已读',
        );
        return $k == '__all' ? $arr : $arr[$k];
    }
    /**
     * 获取用未读消息都是条数
     * @param $memberId
     * @return int
     */
    public function getRemindTotal($memberId){

        $remindModel = Loader::model('messageRemind');
        $counts = $remindModel->count(array('to_member_id' => $memberId, 'to_way'=>1,'is_read'=>0));
        return $counts;

    }

}

